package com.atguigu.tingshu.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    WxMaService wxMaService;
    @Autowired
    RabbitService rabbitService;


    @Override
    public Map<String, Object> wxLogin(String code) {
        //获取OpenId
        WxMaJscode2SessionResult wxMaJscode2SessionResult = null;
        try {
            wxMaJscode2SessionResult = wxMaService.jsCode2SessionInfo(code);
        } catch (WxErrorException e) {
            log.error(e.getMessage(),e);
        }
        String openid = wxMaJscode2SessionResult.getOpenid();

        //与数据库中用户表的openid进行匹配
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openid));
        if (null == userInfo) {
            //当前用户不存在，表示注册
            userInfo = new UserInfo();
            userInfo.setWxOpenId(openid);
            userInfo.setNickname("听友：" + System.currentTimeMillis());
            userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            userInfoMapper.insert(userInfo);
            //给当前用户送福利，给账户充值100元
            //第一种方式：远程调用；第二中方式：异步
            //发送消息的具体内容由谁来决定？：消费者！
            rabbitService.sendMessage(MqConst.EXCHANGE_USER, MqConst.ROUTING_USER_REGISTER, userInfo.getId());

        }
        //当前用户已存在，把用户信息保存到缓存中
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        String userLoginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
        redisTemplate.opsForValue().set(userLoginKey, userInfo, RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.DAYS);
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        return map;
    }

    @Override
    public UserInfoVo getUserInfoVo(Long userId) {
        UserInfoVo userInfoVo = new UserInfoVo();
        UserInfo userInfo = this.getById(userId);
        if (null !=userInfo){
            BeanUtils.copyProperties(userInfo, userInfoVo);
        }
        return userInfoVo;
    }


}
